#=========================================
#     FileName: slave.py
#         Desc:
#       Author: ez~
#        Email: 2511384642@qq.com
#     HomePage: 
#      Version: 0.0.1
#   LastChange: 2021-08-04 16:02:14
#      Descrip:
#
#      从站模拟器
#=========================================

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import sys, serial, random, threading, time


logger = modbus_tk.utils.create_logger(
    name="console", 
    record_format="%(asctime)s\t%(levelname)s\t%(module)s.%(funcName)s\t%(threadName)s\t%(message)s"
)


def run(port):
    """从站模拟程序

    使用Configure Virtual Serial Port Driver创建如下虚拟串口对：
    COM1 --------> COM2
    COM3 --------> COM4
    COM5 --------> COM6
    因当前设备模拟环境不支持一主多从式模拟，因此先使用多主多从多线程模拟

    :param port: 当前模拟主站对应的串口号
    :type port: Serial
    
    """

    server = modbus_rtu.RtuServer(serial.Serial(port))

    try:
        server.start()

        # 添加一个id为1的从站包含一个名为'0'的寄存器区
        slave = server.add_slave(1)
        slave.add_block('0', cst.ANALOG_INPUTS, 0, 2)

        while True:

            # 模拟生成温湿度数据
            temu = random.randint(10, 100)
            humi = random.randint(10, 100)
            value = [temu, humi]
            slave.set_values('0', 0, value)
            values = slave.get_values('0', 0, 2)
            logger.info('salve done: values written: %s\r' % (str(values)))
            
            time.sleep(5)


    finally:
        server.stop()



if __name__ == '__main__':
    PORTS = [
        'COM2',
        'COM4',
        'COM6'
    ]
    threads = []
    for port in PORTS:
        threads.append(
            threading.Thread(target=run, args=(port, ))
        )
    for thread in threads:    
        thread.start()
    # for thread in threads:
    #     thread.join()

